package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.ICreditApplyService;
import com.ruoyi.bizsys.service.ICustAndonLogService;
import com.ruoyi.bizsys.service.ICustBindCardLogService;
import com.ruoyi.bizsys.service.ILoanOrderService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.common.AsyncService;
import com.ruoyi.business.service.ICustomerAndonService;
import com.ruoyi.common.config.EmailConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.vo.EmailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CustomerAndonServiceImpl extends BaseService implements ICustomerAndonService {

    @Autowired
    AsyncService asyncService;

    @Autowired
    ICustAndonLogService custAndonLogService;

    @Autowired
    ICreditApplyService creditApplyService;

    @Autowired
    ILoanOrderService loanOrderService;

    @Autowired
    ICustBindCardLogService custBindCardLogService;

    @Override
    public void sendAndonEamil(CreditFlag creditFlags, String phone, String fullName) {
        JSONObject andonContent = getAndonContent(creditFlags, phone, fullName);
        sendAndonEamil(creditFlags.getType(), andonContent);
    }

    @Override
    public void sendAndonEamil(String type, JSONObject andonContent) {
        try {
            EmailVo emailVo = EmailVo.builder()
                    .subject(type + "审核-客户Andon")
                    .cc(EmailConfig.getAndonAddress().split(","))
                    .addressees(EmailConfig.getAndonAddress().split(","))
                    .param(andonContent)
                    .title(type + "审核-客户Andon").build();
            asyncService.sendCommonEmail(emailVo);
        } catch (Exception e) {
            log.error("邮件发送失败：" + e);
        }
    }

    @Override
    public void sendAndonFeishu(String type, JSONObject content) {
        try {
            asyncService.sendFeishu(EmailConfig.getAndonFeishuName(), type + "审核-客户Andon", content);
        } catch (Exception e) {
            log.error("飞书推送失败：" + e);
        }
    }

    @Override
    public JSONObject getAndonContent(CreditFlag creditFlags, String phone, String fullName) {
        //发送邮箱
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Customer ID", creditFlags.getCustNo());
        jsonObject.put("客户姓名", fullName);
        jsonObject.put("客户手机号", phone);

        jsonObject.put("流水号", creditFlags.getSerialNo());
        if (creditFlags.getOrderFlag() == null) {
            jsonObject.put("卡单原因", "订单标识缺失");
        } else if (creditFlags.getDeviceFlag() == null) {
            jsonObject.put("卡单原因", "设备信息标识缺失");
        } else if (creditFlags.getContactsFlag() == null) {
            jsonObject.put("卡单原因", "通讯录标识缺失");
        } else if (creditFlags.getAppsFlag() == null) {
            jsonObject.put("卡单原因", "Applist标识缺失");
        } else {
            jsonObject.put("卡单原因", "其他");
        }
        return jsonObject;
    }

    @Override
    public void insertAndonLog(CustAndonLog custAndonLog) {
        //查询用户实名
        QueryWrapper<RealNameAuth> realNameAuthQueryWrapper = new QueryWrapper<>();
        realNameAuthQueryWrapper.eq("cust_no", custAndonLog.getCustNo()).select("first_name", "middle_name", "last_name", "user_id");
        RealNameAuth realNameAuth = realNameAuthService.getOne(realNameAuthQueryWrapper);

        if (realNameAuth != null) {
            custAndonLog.setCustName(realNameAuth.getFullName());

            //查询用户手机号
            QueryWrapper<AppUser> appUserQueryWrapper = new QueryWrapper<>();
            appUserQueryWrapper.eq("user_uuid", realNameAuth.getUserId()).select("phone");
            AppUser appUser = appUserService.getOne(appUserQueryWrapper);
            custAndonLog.setPhoneNumber(appUser.getPhone());
        }

        if (custAndonLog.getType().equals(BizConstants.ANDON_TYPE_CREDIT)) {
            //授信按灯
            custAndonLog = creditAndon(custAndonLog);
        } else if (custAndonLog.getType().equals(BizConstants.ANDON_TYPE_LOAN)) {
            //提现按灯
            custAndonLog = loanAndon(custAndonLog);
        } else if (custAndonLog.getType().equals(BizConstants.ANDON_TYPE_BINDCARD)) {
            //绑卡按灯
            custAndonLog = bindBankCardAndon(custAndonLog);
        }

        QueryWrapper<CustAndonLog> custAndonLogQueryWrapper = new QueryWrapper<>();
        custAndonLogQueryWrapper.eq("relation_sn", custAndonLog.getRelationSn());
        custAndonLogQueryWrapper.eq("type", custAndonLog.getType());
        CustAndonLog custAndonLogSelect = custAndonLogService.getOne(custAndonLogQueryWrapper);
        if (custAndonLogSelect != null) {
            return;
        }

        try {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(custAndonLog));
            jsonObject.remove("type");
            jsonObject.remove("params");
            EmailVo emailVo = EmailVo.builder()
                    .addressees(EmailConfig.getAndonAddress().split(","))
                    .cc(EmailConfig.getAndonAddress().split(","))
                    .param(jsonObject)
                    .subject(custAndonLog.getType() + "-客户Andon")
                    .title(custAndonLog.getType() + "-客户Andon").build();
            asyncService.sendCommonEmail(emailVo);
        } catch (Exception e) {
            log.error("邮件发送失败：" + e);
        }

        custAndonLogService.insertCustAndonLog(custAndonLog);
    }


    public CustAndonLog creditAndon(CustAndonLog custAndonLog) {
        QueryWrapper<CreditApply> creditApplyQueryWrapper = new QueryWrapper<>();
        creditApplyQueryWrapper.eq("cust_no", custAndonLog.getCustNo()).last("order by create_time desc limit 1");
        CreditApply creditApply = creditApplyService.getOne(creditApplyQueryWrapper);

        custAndonLog.setRelationSn(creditApply.getApplySerialNo());

        if (creditApply.getApplyStatus().equals(BizConstants.APPLY_STATUS_0_REFUSED)) {
            custAndonLog.setStatus("refused");
        } else if (creditApply.getApplyStatus().equals(BizConstants.APPLY_STATUS_10_CANCEL)) {
            custAndonLog.setStatus("cancel");
        } else if (creditApply.getApplyStatus().equals(BizConstants.APPLY_STATUS_1_PASSED)) {
            custAndonLog.setStatus("success");
        } else {
            custAndonLog.setStatus("pending");
        }
        return custAndonLog;
    }

    public CustAndonLog loanAndon(CustAndonLog custAndonLog) {
        QueryWrapper<LoanOrder> loanOrderQueryWrapper = new QueryWrapper<>();
        loanOrderQueryWrapper.eq("cust_no", custAndonLog.getCustNo()).last("order by create_time desc limit 1");
        LoanOrder loanOrder = loanOrderService.getOne(loanOrderQueryWrapper);

        custAndonLog.setRelationSn(loanOrder.getLoanSerialNo());

        if (loanOrder.getLoanStatus().equals(LoanOrder.LOAN_STATUS_0_APPROVE_REFUSED)) {
            custAndonLog.setStatus("refused");
        } else if (loanOrder.getLoanStatus().equals(LoanOrder.LOAN_STATUS_10_CANCEL) || loanOrder.getLoanStatus().equals(LoanOrder.LOAN_STATUS_8_CLOSE)) {
            custAndonLog.setStatus("cancel");
        } else if (loanOrder.getLoanStatus().equals(LoanOrder.LOAN_STATUS_4_LOAN_SUCCESS)) {
            custAndonLog.setStatus("success");
        } else {
            custAndonLog.setStatus("pending");
        }
        return custAndonLog;
    }

    public CustAndonLog bindBankCardAndon(CustAndonLog custAndonLog) {
        QueryWrapper<CustBindCardLog> custBindCardLogQueryWrapper = new QueryWrapper<>();
        custBindCardLogQueryWrapper.eq("bind_serial_no", custAndonLog.getRelationSn());
        CustBindCardLog custBindCardLog = custBindCardLogService.getOne(custBindCardLogQueryWrapper);

        custAndonLog.setRelationSn(custBindCardLog.getBindSerialNo());

        if (custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_TRANS_SUCCESS)) {
            custAndonLog.setStatus("success");
        } else if (custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_TRANS_FAILED)
                || custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_TRANS_TIMEOUT)
                || custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_BY_OHTERS)
                || custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_GET_AUTH_URL_ERR)
                || custBindCardLog.getTransStatus().equals(BizConstants.BIND_CARD_REPEAT_OPERATION)) {
            custAndonLog.setStatus("fail");
        } else {
            custAndonLog.setStatus("pending");
        }

        if (StringUtils.isNotBlank(custBindCardLog.getRemark()) && custBindCardLog.getRemark().contains("Approved")) {
            custAndonLog.setIsPay("是");
        } else {
            custAndonLog.setIsPay("否");
        }

        custAndonLog.setBankcardNumber(custBindCardLog.getCardNumber());
        return custAndonLog;
    }
}
